package com.open.recruitment.recruit.service.impl;


import com.open.capacity.common.model.SysRecruit;
import com.open.capacity.common.model.SysRole;
import com.open.capacity.common.model.SysUser;
import com.open.capacity.common.web.Result;
import com.open.recruitment.recruit.dao.RUserRoleDao;
import com.open.recruitment.recruit.dao.RecruitDao;
import com.open.recruitment.recruit.service.RecruitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class RecruitServiceImpl implements RecruitService {
    @Autowired
    private RecruitDao recruitDao;

    @Autowired
    private RUserRoleDao rUserRoleDao;


    @Override
    public Result addRecruitInformation(SysRecruit sysRecruit) {
        boolean isHave = isHaveCompany(sysRecruit.getCompanyName());
        if (isHave){
            return Result.succeed(recruitDao.addRecruitInformation(sysRecruit),"添加成功");
        }else {
            return Result.failed("公司名称已存在，请勿重复添加");
        }

    }
    //判断公司名称是否已经存在
    private boolean isHaveCompany(String companyName) {
        List<SysRecruit> list = new ArrayList<>();
        list = recruitDao.isHaveCompany(companyName);
        return list.size() == 0;
    }

    @Override
    public Result updateRecruitInformation(SysRecruit sysRecruit) {
        return Result.succeed(recruitDao.updateRecruitInformation(sysRecruit),"修改成功");
    }

    @Override
    public Result deleteRecruitInformation(long id) {
        return Result.succeed(recruitDao.deleteRecruitInformation(id),"删除成功");
    }

//    @Override
//    public List<SysRecruit> selectAll(Map<String,Object> map) {
//        List<SysRecruit> list = new ArrayList<>();
//        list = recruitDao.selectAll(map);
//        return list;
//    }

    @Override
    public List<SysRecruit> selectCompanyName(Map<String, Object> map) {
        Object userId1 = map.get("userId");
        long userId = 0;
        boolean isAdmin=false; //默认不是管理员
        if(userId1!=null){
            userId = Long.valueOf(map.get("userId").toString());
            Set<SysRole> rolesByUserId = rUserRoleDao.findRolesByUserId(userId);
            Iterator<SysRole> iterator = rolesByUserId.iterator();
            while (iterator.hasNext()){
                SysRole next = iterator.next();
                if(next.getCode().equals("ADMIN")){
                    isAdmin=true;
                    break;
                }
            }
        }

        if(isAdmin) {
            map.remove("userId");
        }else {
            SysUser user = rUserRoleDao.findUserById(userId);
            Long companyId = user.getCompanyId();
            map.remove("userId");
            map.put("companyId",companyId);
        }

        List<SysRecruit> list = new ArrayList<>();
        list = recruitDao.selectCompanyName(map);
        return list;
    }


}
